<template>
  <a-card :bordered="false">
      <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="合同签订日期">
              <a-range-picker
              :allowClear="false"
              v-model="signingDate"
              style="width: 100%"
              @change="signingDateChange"/>
            </a-form-item>
          </a-col>
          <!-- <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="项目名称">
              <select-project-input v-model="queryParam.projectId" placeholder="请选择项目" />
            </a-form-item>
          </a-col> -->
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="采购合同编号">
              <a-input placeholder="请输入采购合同编号" v-model="queryParam.purchaseBill"></a-input>
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="合同申请人">
              <select-user-by-dep placeholder="请选择合同申请人" v-model="queryParam.proposer" />
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="采购单位">
              <select-Company-input placeholder="请选择采购单位" v-model="queryParam.demandCompanName" />
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="供货单位">
              <select-customer-input placeholder="请选择供货单位" v-model="queryParam.supplyCompanName" commercialType="2" />
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="合同状态">
              <j-dict-select-tag type="list" v-model="queryParam.contractStatus" dictCode="purchase_contract_status" placeholder="请选择合同状态" />
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="合同金额">
              <a-input-number :min="0" :precision="0" style="width: 45%" placeholder="请输入合同金额最小值" class="query-group-cust" v-model="queryParam.totalAmountBegin"></a-input-number>
              <span class="query-group-split-cust"></span>
              <a-input-number :min="queryParam.totalAmountBegin" :precision="0" style="width: 45%" placeholder="请输入合同金额最大值" class="query-group-cust" v-model="queryParam.totalAmountEnd"></a-input-number>
            </a-form-item>
          </a-col>
          <!-- <template v-if="toggleSearchStatus"></template> -->
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
              <a-button type="primary" @click="onClearSelected();searchQuery();" icon="search">查询</a-button>
              <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">重置</a-button>
              <!-- <a @click="handleToggleSearch" style="margin-left: 8px">
                {{ toggleSearchStatus ? '收起' : '展开' }}
                <a-icon :type="toggleSearchStatus ? 'up' : 'down'"/>
              </a> -->
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <!-- 查询区域-END -->
    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <a-button type="primary" icon="download" @click="handleExportXls('采购合同台账')" :disabled="isDisabledAuth('erpPurchaseContractStanding:export')">导出</a-button>
      <!-- 高级查询区域 -->
      <!--<j-super-query :fieldList="superFieldList" ref="superQueryModal" @handleSuperQuery="handleSuperQuery"></j-super-query>-->
      <a-popover title="自定义列" trigger="click" placement="leftBottom">
        <template slot="content">
          <a-checkbox-group @change="onColSettingsChange" v-model="settingColumns" :defaultValue="settingColumns">
            <a-row>
              <template v-for="(item,index) in defColumns">
                <template v-if="item.key!='rowIndex'&& item.dataIndex!='action'">
                  <a-col :span="12" :key="index"><a-checkbox :value="item.dataIndex">{{ item.title }}</a-checkbox></a-col>
                </template>
              </template>
            </a-row>
          </a-checkbox-group>
        </template>
        <a style="float: right;"><a-icon type="setting" :style='iconStyle'/></a>
      </a-popover>
    </div>
    <!-- table区域-begin -->
    <div>
      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">
        <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择 <a style="font-weight: 600">{{ selectedRowKeys.length }}</a>项
        <a style="margin-left: 24px" @click="onClearSelected">清空</a>
      </div>
      <a-table
        ref="table"
        size="middle"
        :components="draggableComponent"
        bordered
        rowKey="id"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        class="j-table-force-nowrap"
        :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
        @change="handleTableChange">
        <a slot="purchaseBill" slot-scope="text, record" @click="onDetail(record.id)">{{ text }}</a>
        <a slot="practicalPaidAmount" slot-scope="text, record" @click="onDetailList(record.id)">{{ text }}</a>
      </a-table>
    </div>
    <!-- 采购合同详情开始 -->
    <a-modal
      :maskClosable="false"
      title="采购合同单据详情"
      :width="1350"
      :bodyStyle="{
        padding: '0 24px'
      }"
      :visible="visibleDetail"
      @cancel="handleCancelDetail"
      cancelText="关闭">
      <erp-purchase-contract-form ref="contractForm" :disabled="true" normal></erp-purchase-contract-form>
      <template slot="footer">
        <a-button @click.stop="handleCancelDetail">关闭</a-button>
      </template>
    </a-modal>
    <!-- 采购合同详情结束 -->
    <erp-purchase-contract-standing-penetrate ref="contractStandingPenetrate" />
  </a-card>
</template>
<script>
  import '@/assets/less/TableExpand.less'
  import { mixinDevice } from '@/utils/mixin'
  import { JeecgListMixin } from '@/mixins/JeecgListMixin'
  import {DisabledAuthFilterMixin} from '@/mixins/DisabledAuthFilterMixin'
  import SelectUserByDep from '@/views/scy/components/SelectUserByDep'
  import SelectProjectInput from '@/views/scy/components/SelectProjectInput'
  import SelectCustomerInput from '@/views/scy/components/SelectCustomerInput'
  import SelectCompanyInput from '@/views/scy/components/SelectCompanyInput'
  import moment from 'moment'
  import {getAction} from '@/api/manage'
  import ErpPurchaseContractForm from '@/views/erp/purchase/contract/modules/ErpPurchaseContractForm'
  import ErpPurchaseContractStandingPenetrate from '@/views/scy/penetrate/ErpPurchaseContractStandingPenetrate'
  export default {
    name: 'ErpPurchaseContractStandingList',
    mixins:[JeecgListMixin, mixinDevice, DisabledAuthFilterMixin],
    components: {
      SelectUserByDep,
      SelectProjectInput,
      SelectCustomerInput,
      SelectCompanyInput,
      ErpPurchaseContractForm,
      ErpPurchaseContractStandingPenetrate
    },
    data () {
      return {
        description: '采购合同台账管理页面',
        //表头
        columns:[],
        //列设置
        settingColumns:[],
        // 列定义
        defColumns: [
          {
            title: '序号',
            dataIndex: '',
            key:'rowIndex',
            width:60,
            align:"center",
            customRender:function (t,r,index) {
              return parseInt(index)+1;
            }
          },
          // {
          //   title:'项目名称',
          //   align:"center",
          //   dataIndex: 'projectId_dictText',
          // },
          {
            title:'合同编号',
            align:"center",
            dataIndex: 'purchaseBill',
            width:200,
            ellipsis: true,
            scopedSlots: { customRender: 'purchaseBill' },
          },
          {
            title:'合同名称',
            align:"center",
            width:200,
            ellipsis: true,
            dataIndex: 'contractName',
          },
          {
            title:'合同金额(元)',
            align:"center",
            width:120,
            ellipsis: true,
            dataIndex: 'totalAmount',
          },
          {
            title:'合作单位',
            align:"center",
            width:200,
            ellipsis: true,
            dataIndex: 'supplyCompanName_dictText',
          },
          {
            title:'联系人',
            align:"center",
            width:120,
            ellipsis: true,
            dataIndex: 'supplyEntrustedAgent',
          },
          {
            title:'联系电话',
            align:"center",
            width:120,
            ellipsis: true,
            dataIndex: 'supplyPhoneNumber',
          },
          // {
          //   title:'合同申请人',
          //   align:"center",
          //   dataIndex: 'proposer_dictText',
          // },
          // {
          //   title:'合同申请部门',
          //   align:"center",
          //   dataIndex: 'proposerDeptId_dictText',
          // },
          {
            title:'签订时间',
            align:"center",
            dataIndex: 'signingDate',
            width:140,
            ellipsis: true,
            customRender:function (text) {
              return !text?"":(text.length>10?text.substr(0,16):text)
            }
          },
          {
            title:'到期时间',
            align:"center",
            width:140,
            ellipsis: true,
            dataIndex: 'expireTime',
            customRender:function (text) {
              return !text?"":(text.length>10?text.substr(0,16):text)
            }
          },
          // {
          //   title:'采购团队',
          //   align:"center",
          //   dataIndex: 'teamId_dictText',
          // },
          {
            title:'签订单位',
            align:"center",
            width:200,
            ellipsis: true,
            dataIndex: 'demandCompanName_dictText',
          },
          {
            title:'所属部门/团队',
            width:200,
            ellipsis: true,
            align:"center",
            dataIndex: 'teamId_dictText',
          },
          // {
          //   title:'税率(%)',
          //   align:"center",
          //   dataIndex: 'taxRate',
          // },
          // {
          //   title:'合同状态',
          //   align:"center",
          //   dataIndex: 'contractStatus_dictText',
          // },
          {
            title:'审批状态',
            align:"center",
            width:100,
            ellipsis: true,
            dataIndex: 'bpmStatus_dictText',
          },
          // {
          //   title:'份数',
          //   align:"center",
          //   dataIndex: 'bpmStatus_dictText',
          // },
          // {
          //   title:'存放位置',
          //   align:"center",
          //   dataIndex: 'fileLocation',
          // },
          {
            title:'备注',
            align:"center",
            width:200,
            ellipsis: true,
            dataIndex: 'remark',
          },
          // {
          //   title:'已付合同金额（元）',
          //   align:"center",
          //   dataIndex: 'practicalPaidAmount',
          //   scopedSlots: { customRender: 'practicalPaidAmount' },
          // },
          // {
          //   title:'未付合同金额（元）',
          //   align:"center",
          //   dataIndex: 'unpaidPaidAmount',
          // },
        ],
        url: {
          list: "/api/erp/purchase/statistical/erpPurchaseContractStanding/list",
          exportXlsUrl: "/api/erp/purchase/statistical/erpPurchaseContractStanding/exportXls",
          queryById: '/api/erp/purchase/contract/erpPurchaseContract/queryById'
        },
        dictOptions:{},
        superFieldList:[],
        signingDate: [],
        signingDateStartTime: null,
        signingDateEndTime: null,
        visibleDetail: false,
      }
    },
    created() {
      this.getSuperFieldList();
    },
    methods: {
      moment,
      loadData(arg) {
        if (!this.url.list) {
          this.$message.error('请设置url.list属性!')
          return
        }
        // 加载数据 若传入参数1则加载第一页的内容
        if (arg === 1) {
          this.ipagination.current = 1
        }
        if(this.signingDate.length == 0) {
          this.initMonthDate()
        }
        var params = this.getQueryParams() // 查询条件
        this.loading = true
        getAction(this.url.list, params).then(res => {
          if (res.success) {
            // update-begin---author:zhangyafei    Date:20201118  for：适配不分页的数据列表------------
            this.dataSource = res.result.records || res.result
            if (res.result.total) {
              this.ipagination.total = res.result.total
            } else {
              this.ipagination.total = 0
            }
            //判断是否当前页没有数据且不为第一页
            if (this.dataSource.length == 0 && this.ipagination.current != 1) {
              this.ipagination.current = this.ipagination.current - 1
              this.loadData(this.ipagination.current - 1);
            }
            // update-end---author:zhangyafei    Date:20201118  for：适配不分页的数据列表------------
          }
          if (res.code === 510) {
            this.$message.warning(res.message)
          }
          this.loading = false
        })
      },
      //初始化合同签订日期查询条件
      initMonthDate() {
        let signingDateStartTime = this.getStartTime()
        let signingDateEndTime = this.getEndTime()
        this.signingDate = [moment(signingDateStartTime, 'YYYY-MM-DD'), moment(signingDateEndTime, 'YYYY-MM-DD')]
        this.$set(this.queryParam, 'signingDateStartTime', signingDateStartTime + ' 00:00:00')
        this.$set(this.queryParam, 'signingDateEndTime', signingDateEndTime + ' 23:59:59')
      },
      //查询当前月第一天，返回在字符串
      getStartTime() {
        let date = new Date()
        date.setDate(1) // 将当前时间的日期设置成第一天
        let year= date.getFullYear()  // 得到当前年份
        let month = date.getMonth()  + 1 // 得到当前月份（0-11月份，+1是当前月份）
        month  = month > 10 ? month :'0' + month // 补零
        let day  = date.getDate() // 得到当前天数，实际是本月第一天，因为前面setDate(1) 设置过了
        return year +'-'+ month +'-'+ day // 这里传入的是字符串
      },
      //查询当前月最后一天，返回字符串
      getEndTime(){
        let  date  = new Date()
        let year = date.getFullYear()
        let month = date.getMonth() +1
        // 这里传入的是整数时间，返回的是下个月的第一天，因为月份是0-11
        let nextMonthFirthDay = new Date(year,month,1) // 下个月的第一天
        let oneDay = 1000*60 * 60 * 24 // 一天的时间毫秒数
        let endDay = new Date(nextMonthFirthDay - oneDay)
        let day = endDay.getDate() // 本月最后一天
        // 这里传入的是字符串格式的时间，返回的是传入字符串的时间
        return year + '-' + month + '-' + day
      },
      initDictConfig(){
      },
      getSuperFieldList(){
        let fieldList=[];
        // fieldList.push({type:'string',value:'projectId',text:'项目名称',dictCode:''})
        fieldList.push({type:'string',value:'purchaseBill',text:'采购合同编号',dictCode:''})
        fieldList.push({type:'string',value:'proposer',text:'合同申请人',dictCode:''})
        fieldList.push({type:'string',value:'proposerDeptId',text:'合同申请部门',dictCode:''})
        fieldList.push({type:'date',value:'signingDate',text:'合同签订日期'})
        fieldList.push({type:'string',value:'teamId',text:'采购团队',dictCode:''})
        fieldList.push({type:'string',value:'demandCompanName',text:'采购单位',dictCode:''})
        fieldList.push({type:'string',value:'supplyCompanName',text:'供货单位',dictCode:''})
        fieldList.push({type:'BigDecimal',value:'totalAmount',text:'合同金额（元）',dictCode:''})
        fieldList.push({type:'BigDecimal',value:'taxRate',text:'税率（%）',dictCode:''})
        fieldList.push({type:'string',value:'contractStatus',text:'合同状态',dictCode:''})
        fieldList.push({type:'string',value:'bpmStatus',text:'审批状态',dictCode:''})
        fieldList.push({type:'BigDecimal',value:'practicalPaidAmount',text:'已付合同金额（元）',dictCode:''})
        fieldList.push({type:'BigDecimal',value:'unpaidPaidAmount',text:'未付合同金额（元）',dictCode:''})
        this.superFieldList = fieldList
      },
      signingDateChange(date, dateString) {
        this.$set(this.queryParam, 'signingDateStartTime', dateString[0] + ' 00:00:00')
        this.$set(this.queryParam, 'signingDateEndTime', dateString[1] + ' 23:59:59')
      },
      searchReset() {
        this.signingDate = []
        this.queryParam = {}
        this.loadData(1)
      },
      onDetail(billId) {
        this.visibleDetail = true
        this.$nextTick(()=>{
          const id = billId;
          getAction(this.url.queryById, { id }).then((res) => {
            if (res.success) {
              const model = res.result
              this.$refs.contractForm.edit(model);
            }
          })
        });
      },
      handleCancelDetail() {
        this.visibleDetail = false
      },
      onDetailList(billId) {
        //查询数据
        this.$refs.contractStandingPenetrate.contractId = billId
        this.$refs.contractStandingPenetrate.activeKey = '1'
        this.$refs.contractStandingPenetrate.callback(1)
        //打开弹窗
        this.$refs.contractStandingPenetrate.visible = true
      }
    }
  }
</script>
<style scoped>
  @import '~@assets/less/common.less';
</style>
